package com.example.excel;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

public class DateTes {
    public static byte[] picture(String date) throws Exception {
        int width = 472;
        int height = 110;
        SealFont font = new SealFont();
        font.setFontText(date);
        //1.画布
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        int size = 40;
        font.setFontSize(size);
        Graphics2D g2d = bi.createGraphics();
        g2d.setPaint(Color.BLACK);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Font f = new Font(font.getFontFamily(), Font.PLAIN, font.getFontSize());
        g2d.setFont(f);
        //获取文字高宽
        FontMetrics fm = new JLabel().getFontMetrics(f);
        int w = fm.stringWidth(font.getFontText()), h = fm.getHeight();
        g2d.drawString(font.getFontText(), (float) (width-w)/2+2, (float) (height-h)/3+h);
        return buildBytes(bi);
    }

    public static byte[] buildBytes(BufferedImage image) throws Exception {
        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
            //bufferedImage转为byte数组
            ImageIO.write(image, "png", outStream);
            return outStream.toByteArray();
        }
    }
}
